/*
 * Copyright 2012-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package consumer.consumer;

import java.math.BigDecimal;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import consumer.entity.ConsEntity;
import consumer.entity.ProdEntity;
import consumer.enums.ApiErrorEnum;
import consumer.enums.OrderStatusEnum;
import consumer.exception.ApiException;
import consumer.mapper.ConsumerMapper;
import consumer.util.JsonUtil;

@Component
public class Consumer {
	private Logger LOGGER = LogManager.getLogger();
	@Autowired
	private ConsumerMapper consumerMapper;

	@JmsListener(destination = "order.timeout.close")
	public void orderTimeOutClose(String text) {
		LOGGER.info("orderTimeOutClose接收到的订单号【{}】", text);
		// 查询数据判断状态是否为待付款
		ConsEntity consEntity = checkOrderExists(text);
		ConsEntity consEntityTwo = new ConsEntity();
		if (!OrderStatusEnum.WAIT_PAYMENT.getCode().equals(consEntity.getStatus())) {
			throw new ApiException(ApiErrorEnum.ERROR_1002);
		}
		// 如果状态是待付款，关闭订单
		if(OrderStatusEnum.WAIT_PAYMENT.getCode().equals(consEntity.getStatus())) {
			consEntityTwo.setStatus(OrderStatusEnum.CLOSE.getCode());
			
		}
	}

	@JmsListener(destination = "add.jd")
	public void adJd(String text) {
		LOGGER.info("adJd接收到JSON【{}】", text);
		//从数据库查询一下订单量否已经添加京豆
		ProdEntity prodEntity = JsonUtil.jsonToBean(text, ProdEntity.class);
		// 价格*10%
		BigDecimal sumPrice = new BigDecimal(prodEntity.getNumber()).multiply(prodEntity.getPrice())
				.multiply(new BigDecimal(0.1));
		//四舍五入往上取整
		Integer intSumPrice = sumPrice.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
		LOGGER.info("总价格【{}】", intSumPrice);
		// 构建JD对象
		ConsEntity consEntity = new ConsEntity();
		consEntity.setJDNumber(intSumPrice);
		consEntity.setUserId(text);
		consEntity.setOrderNumber(text);
//		consEntity.ge
		// 保存到数据库
		consumerMapper.addCons(consEntity);

	}
	private ConsEntity checkOrderExists(String orderNumber) {
		// 检查订单是否存在
//		ProdEntity prodEntity = ConsumerMapper.selectByOrderNumber(orderNumber);
		ConsEntity consEntity = consumerMapper.selectByOrderNumber(orderNumber);
		if (consEntity == null) {
			throw new ApiException(ApiErrorEnum.ERROR_1001);
		}
		return consEntity;
	}
}
